package cn.seaboot.commons.ftp.pool;

import cn.seaboot.commons.ftp.FtpSource;
import cn.seaboot.commons.ftp.FtpProperties;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.io.IOException;

/**
 * FTPClient 工厂（ 连接工厂）
 * <p>
 *
 * @author Mr.css
 * @version 2021-02-20 11:04
 */
public class PooledFTPClientFactory extends BasePooledObjectFactory<FTPClient> {

    /**
     * 封装基于未池化的 FtpClient
     */
    private final FtpSource ftpSource;

    public PooledFTPClientFactory(FtpProperties properties) {
        this.ftpSource = new FtpSource(properties);
    }

    /**
     * 连接池函数——创建FTPClient对象
     */
    @Override
    public FTPClient create() throws IOException {
        return ftpSource.createFTPClient();
    }

    /**
     * 连接池函数——FTPClient对象池化
     */
    @Override
    public PooledObject<FTPClient> wrap(FTPClient ftpClient) {
        return new DefaultPooledObject<>(ftpClient);
    }

    /**
     * 连接池函数——销毁FTPClient对象
     */
    @Override
    public void destroyObject(PooledObject<FTPClient> ftpPooled) {
        FTPClient client = ftpPooled.getObject();
        ftpSource.closeFTPClient(client);
    }

    /**
     * 连接池函数——验证FtpClient有效性
     */
    @Override
    public boolean validateObject(PooledObject<FTPClient> ftpPooled) {
        if (ftpPooled != null) {
            return this.ftpSource.validateFtpClient(ftpPooled.getObject());
        }
        return false;
    }
}
